import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_project/common/route_page/route_name.dart';

import '../common/utils/screen_size_utils.dart';
import '../config/asphere_refresh_utils.dart';
import '../config/common_string_config.dart';
import '../config/empty_img_view.dart';
import '../config/theme_color.dart';
import '../home/home_video_details_page.dart';
import '../home/home_video_list_model.dart';
import '../requst/dio_http_utils.dart';

class WorksTabListPage extends StatefulWidget {
  final CommonEditType type;

  const WorksTabListPage({required this.type, super.key});

  @override
  State<WorksTabListPage> createState() => _WorksTabListPageState();
}

class _WorksTabListPageState extends State<WorksTabListPage> {
  List dataList = [];
  int page = 0;
  EasyRefreshController easyRefreshController = EasyRefreshController();

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(top: 10),
      child: dataList.isNotEmpty
          ? AsphereRefreshUtils.refreshWidget(
             context: context,
              refreshController: easyRefreshController,
              startRefresh: () {
                if (dataList.isNotEmpty) {
                  dataList.clear();
                }
                page = 0;
                getListData();
              },
              startLoad: () {
                page++;
                getListData();
              },
              childWidget: GridView.builder(
                  padding:
                      const EdgeInsets.only(left: 10, right: 10, bottom: 0),
                  itemCount: dataList.length,
                  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 2,
                      crossAxisSpacing: 10,
                      mainAxisSpacing: 10,
                      childAspectRatio: 1 / 1),
                  itemBuilder: (context, index) {
                    VideoListVideosModel itemModel = dataList[index];
                    double imgWidth =
                        ScreenSizeUtils.deviceScreenWidth(context);
                    imgWidth = (imgWidth - 10 * 3) / 2.0;
                    String status = itemModel.status == 8
                        ? "创作失败\n抱歉，请重新创作"
                        : '审核未通过\n请修改后重新创作';
                    String imgUrl =
                        widget.type == CommonEditType.videoType //0代表图片  1代表视频
                            ? (itemModel.webp ?? '')
                            : (itemModel.url ?? '');
                    return GestureDetector(
                      onTap: () {
                        RouteNames.push(HomeVideoDetailsPage(
                          id: itemModel.id ?? 0,
                          type: widget.type == CommonEditType.videoType ? 1 : 0,
                        ));
                      },
                      child: Container(
                        color: ThemeColor.mainBgColor,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            EmptyImgView.commonEmptyImg(
                                url: imgUrl,
                                imgHeight: 120,
                                imgWidth: imgWidth,
                                status: status),
                            const SizedBox(
                              height: 10,
                            ),
                            Text(
                              itemModel.prompt ?? '',
                              overflow: TextOverflow.ellipsis,
                              maxLines: 1,
                            ),
                          ],
                        ),
                      ),
                    );
                  }),
            )
          : Container(),
    );
  }

  @override
  void initState() {
    super.initState();
    getListData();
  }

  getListData() async {
    Map<String, dynamic>? dataMap = {
      'Limit': 6,
      'MediaType': widget.type == CommonEditType.videoType ? 1 : 0,
      'Offset': page * 6,
      'SortFieldName': 'CreateTime',
      'SortType': 'desc'
    };
    var res = await HttpDioUtils.request('media/getAccountHistoryMedia',
        params: dataMap);
    VideoListModel videoListModel = VideoListModel.fromJson(res);
    if (widget.type == CommonEditType.videoType) {
      List resList = videoListModel.resp?.videos ?? [];
      if (page > 0 && resList.isEmpty) {
        easyRefreshController.finishLoad(IndicatorResult.noMore, true);
        return;
      }
      dataList.addAll(videoListModel.resp?.videos ?? []);
    } else {
      List resList = videoListModel.resp?.videos ?? [];
      if (page > 0 && resList.isEmpty) {
        easyRefreshController.finishLoad(IndicatorResult.noMore, true);
        return;
      }
      dataList.addAll(videoListModel.resp?.imgList ?? []);
    }
    if (mounted) {
      setState(() {});
    }
  }
}
